/* eslint-disable */
import React, { useState, Fragment, useEffect } from "react"
import { Tooltip } from 'antd'
import { FormattedMessage } from 'react-intl'

// 文档目录菜单
const DocDirectoryMenu = ({ tableOfContents, pageContext }) => {
  const { lang, slug, relativePath, realSlug } = pageContext
  const docMenu = tableOfContents.replace(/\/#/g, '#')
  const [scrollTop, setScrollTop] = useState(0)
  const issueHref = `https://gitee.com/enmotech/mogdb-docs/issues/new?&description=原始文件：[/${relativePath}](https://docs.mogdb.io${realSlug || slug})`

  useEffect(() => {
    // 获取当前滚动的高度
    scrollListenerFunc()
    window.addEventListener("scroll", scrollListenerFunc)
    return () => {
      // 移除事件
      window.removeEventListener("scroll", scrollListenerFunc)
    }
  }, [])
  function scrollListenerFunc () {
    const scrollTopVal = document.documentElement.scrollTop || document.body.scrollTop
    setScrollTop(scrollTopVal)
  }
  function scrollToTop () {
    try {
      window.scroll({
        behavior: 'smooth',
        top: 0,
      })
    } catch(err) {
      if (err instanceof TypeError) {
        window.scroll(0, 0)
      } else {
        throw err
      }
    }
  }

  // 控制文档目录菜单是否展示
  const [docDirectoryMenuVisible, setDocDirectoryMenuVisible] = useState(false)
  return (
    <Fragment>
      {docDirectoryMenuVisible &&
        <div className="right-container">
          <section className="doc-directory-box">
            <div className="hide-directory-btn" onClick={() => setDocDirectoryMenuVisible(false)}></div>
            <div className="directory-content">
              <div dangerouslySetInnerHTML={{ __html: docMenu }} />
            </div>
          </section>
        </div>}
      
      <div className="doc-right-btns">
        <a className="doc-directory-btn issue" target="_blank" href={issueHref} rel="noreferrer">
          <FormattedMessage id="pageMenu.issue"/>
        </a>
        {!docDirectoryMenuVisible &&
          <Tooltip placement="left" title={<FormattedMessage id="pageMenu.nav"/>}>
            <div className="doc-directory-btn nav" onClick={() => setDocDirectoryMenuVisible(true)}></div>
          </Tooltip>
        }
        {scrollTop >= 400 && 
          <Tooltip placement="left" title={<FormattedMessage id="pageMenu.backtop"/>}>
            <div className="doc-directory-btn backtop" onClick={() => scrollToTop()}></div>
          </Tooltip>
        }
      </div> 
    </Fragment>
  )
}
export default DocDirectoryMenu
